<template>
  <div class="form-preview">
    <el-form
      :model="formData"
      :label-width="currentFormConfig.labelWidth || '100px'"
      :label-position="currentFormConfig.labelPosition || 'right'"
      :size="currentFormConfig.size || 'default'"
      :disabled="currentFormConfig.disabled || false"
      :inline="currentFormConfig.inline || false"
    >
      <el-row :gutter="20">
        <el-col
          v-for="component in currentFormConfig.components"
          :key="component.id"
          :span="(component.span || 12) * 2"
        >
          <el-form-item
            :label="component.label"
            :prop="component.name"
            :required="component.required"
          >
            <FormComponentRenderer
              :component="component"
              v-model="formData[component.name]"
              :preview="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, watch } from 'vue'
import { useFormDesignerStore } from '@/stores/form/formDesigner'
import FormComponentRenderer from './FormComponentRenderer.vue'

// 定义props
interface Props {
  formConfig?: any
  initialData?: Record<string, any> // 用于数据回显的初始数据
}

const props = withDefaults(defineProps<Props>(), {
  formConfig: undefined,
  initialData: () => ({})
})

const formDesignerStore = useFormDesignerStore()

// 当前表单配置 - 优先使用props，否则使用store
const currentFormConfig = computed(() => {
  if (props.formConfig) {
    return props.formConfig
  }
  return formDesignerStore.currentForm
})

// 表单数据
const formData = reactive<Record<string, any>>({})

// 初始化表单数据
const initFormData = () => {
  // 先清空现有数据
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  const components = currentFormConfig.value.components || []
  components.forEach(component => {
    if (component.name) {
      // 优先使用传入的初始数据，否则使用默认值
      if (props.initialData && props.initialData[component.name] !== undefined) {
        formData[component.name] = props.initialData[component.name]
      } else {
        formData[component.name] = (component as any).defaultValue || ''
      }
    }
  })
  
  console.log('表单数据初始化完成:', formData)
}

// 监听组件变化和初始数据变化，重新初始化表单数据
watch([currentFormConfig, () => props.initialData], initFormData, { immediate: true, deep: true })

// 暴露获取表单数据的方法给父组件
const getFormData = () => {
  return { ...formData }
}

// 暴露方法给父组件
defineExpose({
  getFormData
})
</script>

<style scoped lang="scss">
.form-preview {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  
  .el-form {
    max-width: none;
  }
}
</style>
